import cv2 as cv
import numpy as np

# -------------------------读取视频文件和显示视频帧------------------------

cap = cv.VideoCapture('video.mp4')

# 循环读取视频帧，并显示
while cap.isOpened():
    # 读取视频帧
    ret, frame = cap.read()
    if ret == True:
        # 显示视频帧
        cv.imshow('Frame', frame)

        # 等待按键输入
        if cv.waitKey(25) & 0xFF == ord('q'): #按下就退出，没按下就每25ms刷新一次
            break
    else:
        break

cap.release()
cv.destroyAllWindows()

# ----------------------保存视频文件-----------------------

cap = cv.VideoCapture('video.mp4')

# 获取图像属性（宽和高），并将其转换为int类型
width = int(cap.get(cv.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT))
print(width, height)

# 设置编码格式
fourcc = cv.VideoWriter_fourcc(*'H264')

# 创建视频写入对象
out = cv.VideoWriter('copy.mp4', fourcc, 30.0, (width, height)) # 保存视频文件名，编码格式，帧率，图像尺寸

# 循环读取视频帧，并保存
while cap.isOpened():
    # 读取视频帧
    ret, frame = cap.read()
    if ret == True:
        # 保存视频帧
        out.write(frame)

    else:
        break

cap.release()
out.release()
cv.destroyAllWindows()